package com.yihaodian.cluster;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.yihaodian.api.common.json.GsonWrapper;

/**
 * local cluster state gateway.
 * 
 */
public class ClusterStateLocal {
	private static Logger logger = Logger
			.getLogger(DefaultClusterService.class);

	public static final String default_file = "/var/www/data/mars/clusterstate.json";

	String state_file = default_file;

	public ClusterStateLocal() {

	}

	public ClusterStateLocal(String file) {
		this.state_file = file;
	}

	public ClusterState read() {
		Gson gson = GsonWrapper.getGson();

		File file = new File(state_file);
		if (file.exists()) {
			Reader reader;
			try {
				reader = new FileReader(file);

				ClusterState cs = gson.fromJson(reader, ClusterState.class);
				return cs;

			} catch (Exception e) {
				logger.error("can not read local cluster state", e);
			}
		}

		return null;
	}

	public void write(ClusterState cs) throws IOException {
		Gson gson = GsonWrapper.getGson();

		String data = gson.toJson(cs);
		File file = new File(state_file);

		if (file.exists()) {
			file.renameTo(new File(state_file + "." + new Date()));
		}

		FileUtils.write(file, data, "utf-8");
	}

}
